/**
  * 批量下载  前端压缩功能
  * getFileApi 获取文件api
  */
<template>
  <div>
    <el-dialog title="导出进度" :visible.sync="dialogVisible" width="300px" modal show-close="false" close-on-click-modal="false">
      <div style="text-align: center;">
        <el-progress type="circle" :percentage="percentage" :status="percentage === 100 ? 'success' : ''" />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button v-if="percentage === 100" type="primary" @click="dialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Jszip from 'jszip';
import { saveAs } from 'file-saver';
import { getDownloadFile } from '@/extend/api/table';
import {
  api_POST_EventsManagementReport // 导出参赛证
} from '@/extend/api/gameswaggerApi/app.js';
export default {
  name: 'DownLoadPdfZip',
  props: {
    // zip文件name
    zipName: {
      type: String,
      default: ''
    },
    fileType: {
      type: String,
      default: 'pdf'
    }
  },
  data() {
    return {
      zip: '',
      // 下载文件api参数
      zipDataList: [],
      typeList: {
        pdf: 'application/pdf'
      },
      dialogVisible: false,
      percentage: 0
    };
  },
  methods: {
    // 执行打包
    downloadFileList(zipDataList) {
      this.zip = new Jszip();
      this.zipDataList = zipDataList;
      this.dialogVisible = true;
      this.percentage = 0;
      this.getDownFile(0).then(res => {
        this.zip.generateAsync({ type: 'blob' }).then((content) => {
          console.log(content);
          saveAs(content, this.zipName + '.zip');
          this.percentage = 100;
        });
      }, error => {
        console.error(error);
      });
    },
    async getDownFile(index) {
      const _datas = this.zipDataList[index];
      console.log(index);
      const _fileData = await this.getFileApi(_datas);
      console.log(_fileData);
      await this.getFileByUrl(_fileData.tempUrl, index);
      index++;
      if (index < this.zipDataList.length) {
        await this.getDownFile(index);
      }
      return true;
    },
    // 获取文件 保存blob格式
    getFileByUrl(url, index) {
      return new Promise((resolve, reject) => {
        getDownloadFile(url).then(res => {
          this.zip.file((this.zipDataList[index].fileName ? this.zipDataList[index].fileName : index) + '.pdf', res);
          this.percentage = Math.floor(index / (this.zipDataList.length + 1) * 100);
          resolve(res);
        }, error => {
          console.error(error);
          reject(error);
        });
      });
    },
    getFileApi(datas) {
      return api_POST_EventsManagementReport(datas);
    }
  }
};
</script>
